package tech.lq0.dreamaticvoyage.item.fukamizutech.tool;

import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.jetbrains.annotations.Nullable;
import tech.lq0.dreamaticvoyage.block.entity.AbstractPylonBlockEntity;
import tech.lq0.dreamaticvoyage.block.entity.AbstractUCEProviderBlockEntity;
import tech.lq0.dreamaticvoyage.capability.ModCapabilities;

import java.util.List;

@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.FORGE)
public class FukamizuBreadWrench extends Item {

    public FukamizuBreadWrench() {
        super(new Properties().stacksTo(1).fireResistant());
    }

    @Override
    public void appendHoverText(ItemStack pStack, @Nullable Level pLevel, List<Component> pTooltipComponents, TooltipFlag pIsAdvanced) {
        pTooltipComponents.add(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench").withStyle(ChatFormatting.GRAY));
    }

    @Override
    public void inventoryTick(ItemStack pStack, Level pLevel, Entity pEntity, int pSlotId, boolean pIsSelected) {
        super.inventoryTick(pStack, pLevel, pEntity, pSlotId, pIsSelected);
        if (pStack.getTag() != null && pStack.getTag().contains("Machine")) {
            var array = pStack.getTag().getIntArray("Machine");
            if (!(pLevel.getBlockEntity(new BlockPos(array[0], array[1], array[2])) instanceof AbstractUCEProviderBlockEntity)) {
                pStack.removeTagKey("Machine");
            }
        }
    }

    @Override
    public InteractionResult useOn(UseOnContext context) {
        var pos = context.getClickedPos();
        var itemStack = context.getItemInHand();
        var player = context.getPlayer();
        var level = context.getLevel();
        var blockEntity = level.getBlockEntity(pos);

        if (blockEntity == null) return InteractionResult.FAIL;
        if (player == null) return InteractionResult.FAIL;

        if (blockEntity.getCapability(ModCapabilities.UMISU_CURRENT_ENERGY_CAPABILITY).isPresent()) {
            if (player.isShiftKeyDown()) {
                // shift右键
                if (blockEntity instanceof AbstractUCEProviderBlockEntity) {
                    // 扳手只能绑定能量提供者
                    itemStack.getOrCreateTag().putIntArray("Machine", new int[]{pos.getX(), pos.getY(), pos.getZ()});
                    player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.bound",
                            pos.getX() + ", " + pos.getY() + ", " + pos.getZ()).withStyle(ChatFormatting.GREEN), true);
                } else {
                    player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.not_provider")
                            .withStyle(ChatFormatting.RED), true);
                    return InteractionResult.FAIL;
                }
            } else {
                // 直接右键
                if (!itemStack.hasTag() || !itemStack.getOrCreateTag().contains("Machine")) {
                    player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.not_bounded")
                            .withStyle(ChatFormatting.RED), true);
                    return InteractionResult.FAIL;
                }

                var tag = itemStack.getOrCreateTag();
                var array = tag.getIntArray("Machine");

                if (array.length != 3) {
                    player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.not_bounded")
                            .withStyle(ChatFormatting.RED), true);
                    return InteractionResult.FAIL;
                }

                // 扳手绑定的方块需要是能量塔才能进行下一步操作
                if (level.getBlockEntity(new BlockPos(array[0], array[1], array[2])) instanceof AbstractUCEProviderBlockEntity uceProviderBlockEntity) {
                    byte xDiff = (byte) (pos.getX() - array[0]);
                    byte yDiff = (byte) (pos.getY() - array[1]);
                    byte zDiff = (byte) (pos.getZ() - array[2]);

                    if (xDiff == 0 && yDiff == 0 && zDiff == 0) {
                        // 不能绑定自己
                        player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.self_bound")
                                .withStyle(ChatFormatting.RED), true);
                        return InteractionResult.FAIL;
                    } else if (!uceProviderBlockEntity.canBind(new byte[]{xDiff, yDiff, zDiff})) {
                        // 距离限制
                        player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.too_far")
                                .withStyle(ChatFormatting.RED), true);
                        return InteractionResult.FAIL;
                    }

                    if (level.getBlockEntity(pos) instanceof AbstractPylonBlockEntity pylonBlock &&
                            uceProviderBlockEntity instanceof AbstractPylonBlockEntity pylonBlockEntity &&
                            pylonBlockEntity.getPylonLevel() <= pylonBlock.getPylonLevel()) {
                        // 只有高级能量塔才能绑定低级能量塔
                        player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.wrong_level",
                                pylonBlockEntity.getPylonLevel(), pylonBlock.getPylonLevel()).withStyle(ChatFormatting.RED), true);
                        return InteractionResult.FAIL;
                    }

                    if (uceProviderBlockEntity.hasConnection(new byte[]{xDiff, yDiff, zDiff})) {
                        // 右键已连接方块时，移除现有连接
                        uceProviderBlockEntity.removeConnection(new byte[]{xDiff, yDiff, zDiff});
                        uceProviderBlockEntity.setChanged();
                        player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.disconnected")
                                .withStyle(ChatFormatting.YELLOW), true);
                    } else {
                        // 绑定数量限制
                        if (!uceProviderBlockEntity.canBindMore()) {
                            player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.max_count")
                                    .withStyle(ChatFormatting.RED), true);
                            return InteractionResult.FAIL;
                        }
                        // 满足条件，进行绑定
                        uceProviderBlockEntity.addConnection(new byte[]{xDiff, yDiff, zDiff});
                        uceProviderBlockEntity.setChanged();
                        player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.uce_bound",
                                pos.getX() + ", " + pos.getY() + ", " + pos.getZ()).withStyle(ChatFormatting.GREEN), true);
                    }
                } else {
                    player.displayClientMessage(Component.translatable("des.dreamaticvoyage.fukamizu_bread_wrench.not_provider")
                            .withStyle(ChatFormatting.RED), true);
                }
            }

            return InteractionResult.SUCCESS;
        }
        return InteractionResult.FAIL;
    }

    @SubscribeEvent
    public static void rightClickBlock(PlayerInteractEvent.RightClickBlock event) {
        var itemStack = event.getItemStack();
        if (!(itemStack.getItem() instanceof FukamizuBreadWrench)) return;

        var pos = event.getPos();
        var level = event.getLevel();
        var blockEntity = level.getBlockEntity(pos);
        if (blockEntity == null) return;

        // 若右键方块存在对应属性，取消对应右键事件
        if (blockEntity.getCapability(ModCapabilities.UMISU_CURRENT_ENERGY_CAPABILITY).isPresent()) {
            event.setUseBlock(Event.Result.DENY);
        }
    }
}
